package cont

import (
	"github.com/labstack/echo"
	"strconv"
	errs "tacitus/library/error"
	resp "tacitus/library/response"
)

// 显示指定分类的下级分类，为0时显示根分类
func ShowCategoryListHandler(c echo.Context) error {
	i := new(Category)
	if err := c.Bind(i); err != nil {
		return err
	}
	s := x.Where("parent_id = ?", i.ParentID)
	if i.Type != "" {
		s.Where("type = ?", i.Type)
	}
	data := make([]Category, 0)
	if err := s.Find(&data); err != nil {
		return err
	}
	return resp.Data(c, data)
}

// 显示指定分类的分类树(包含当前节点)
func ShowCategoryTreeHandler(c echo.Context) error {
	i := new(Category)
	if err := c.Bind(i); err != nil {
		return err
	}
	if i.ID == 0 {
		return errs.Called("分类编号不能为空")
	}
	current := new(Category)
	if ok, err := x.Where("id = ?", i.ID).Get(current); err != nil {
		return err
	} else if !ok {
		return errs.Called("指定的分类不存在")
	}
	data := make([]Category, 0)
	if err := x.Where("`path` LIKE ?", current.Path+"%").OrderBy("weight DESC").Find(&data); err != nil {
		return err
	}
	res, _ := HangCategoryNode(*current, data)
	return resp.Data(c, res)
}

// 显示指定分类下的内容列表，包含下级分类的内容
func ShowContentListHandler(c echo.Context) error {
	i := new(struct{
		Content
		Sort string `json:"sort"`
		resp.PageFields
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	s := x.NewSession()
	if i.CateID != 0 {
		cis := []int{i.CateID}
		if err := x.Table(new(Category)).Cols("id").Where("`path` LIKE ?", "%/"+strconv.Itoa(i.CateID)+"/%").Find(&cis); err != nil {
			return err
		}
		s = x.In("cate_id", cis)
	}
	if i.Type != "" {
		s.Where("type = ?", i.Type)
	}
	s.OrderBy("create_time DESC")
	data := make([]Content, 0)
	count, err := s.Omit("content", "file").Limit(i.Size(), i.Offset()).FindAndCount(&data)
	if err != nil {
		return err
	}
	return resp.Page(c, data, *i.SetItemCount(int(count)))
}

// 显示指定内容的详情并添加点击量
func ShowContentDetailHandler(c echo.Context) error {
	i := new(Content)
	if err := c.Bind(i); err != nil {
		return err
	}
	if i.ID == 0 {
		return errs.Called("内容编号不能为空")
	}
	data := new(Content)
	if _, err := x.ID(i.ID).Get(data); err != nil {
		return err
	}
	if data.ID == 0 {
		return errs.Called("指定编号的内容不存在")
	}
	if _, err := x.Exec("UPDATE "+i.TableName()+" SET `hits` = `hits` + 1 WHERE `id` = ?", i.ID); err != nil {
		return err
	}
	return resp.Data(c, data)
}

// 评价内容，支持或者反对
func EvaluateContentHandler(c echo.Context) error {
	i := new(Content)
	if err := c.Bind(i); err != nil {
		return err
	}
	if i.ID == 0 {
		return errs.Called("内容编号不能为空")
	}
	// 不反对就是赞成
	query := "UPDATE "+i.TableName()+" SET "
	if i.Oppose > 0 {
		query += "`oppose` = `oppose` + 1"
	} else {
		query += "`support` = `support` + 1"
	}
	if res, err := x.Exec(query+" WHERE `id` = ?", i.ID); err != nil {
		return err
	} else if l, err := res.RowsAffected(); err != nil {
		return err
	} else if l == 0 {
		return errs.Called("要评价的内容不存在")
	}
	return nil
}